package com.offcn.utils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.InputStream;

/**
 * @author: Mr.Chu
 * @create: 2021-06-08 21:10
 * @Description //TODO  MyBatis的工具类
 **/

public class MyBatisUtils {
    public static SqlSessionFactory factory;
    static{
        try {
            InputStream inputStream = Resources.getResourceAsStream("SqlMapConfig.xml");
            //factory重量级别的对象，mybatis框架只需要一个。工厂不需要关闭
            factory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //获得一个SqlSession对象
    public static SqlSession openSession(boolean autocommit) {//
        SqlSession sqlSession = factory.openSession(autocommit);//boolean autocommit:如果返回的是true就是true，反则F
        return sqlSession;
    }
    //手动管理事务
    public static SqlSession openSession() {
        SqlSession sqlSession = factory.openSession();
        return sqlSession;
    }
    //释放资源
    public static void closeSqlSession(SqlSession sqlSession) {
        sqlSession.close();
    }
}
